import { createDeferred, isEmpty } from '@jecloud/utils';
import { useI18n } from '@/service/helper';

/**
 * 账号登录验证
 */
export function accountLoginValidate({ model }) {
  const { t } = useI18n();
  const errors = [];
  if (isEmpty(model.account)) {
    errors.push(t('login.validate.account'));
  } else if (isEmpty(model.password)) {
    errors.push(t('login.validate.password'));
  }
  return validate(errors);
}

/**
 * 动态登录验证
 */
export function dynamicLoginValidate({ model }) {
  return phoneValidate(model.phone).then(() => captchaValidate(model.captcha));
}

/**
 * 验证码验证
 */
export function captchaValidate(captcha) {
  const { t } = useI18n();
  const errors = [];
  if (!/^\d{6}$/.test(captcha)) {
    errors.push(t('login.validate.captcha'));
  }
  return validate(errors);
}
/**
 * 验证手机号
 * @param {*} phone
 * @returns
 */
export function phoneValidate(phone) {
  const { t } = useI18n();
  const errors = [];
  if (!/^1[3456789]\d{9}$/.test(phone)) {
    errors.push(t('login.validate.phone'));
  }
  return validate(errors);
}

/**
 * 重置密码校验
 * @param {Object} params
 * @param {Object} params.model 数据
 * @param {Boolean} params.oldPassword 是否校验旧密码
 * @returns
 */
export function resetPasswordValidate({ model, oldPassword = false }) {
  const { t } = useI18n();
  const errors = [];
  if (
    (oldPassword && isEmpty(model.oldPassword)) ||
    isEmpty(model.newPassword) ||
    isEmpty(model.confirmPassword)
  ) {
    errors.push(t('login.validate.password'));
  } else if (model.newPassword !== model.confirmPassword) {
    errors.push(t('login.validate.passwords'));
  } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/.test(model.newPassword)) {
    errors.push(t('login.validate.passwordRules'));
  }
  return validate(errors);
}

/**
 * 校验提醒
 * @param {*} errors
 * @returns
 */
function validate(errors = []) {
  const deferred = createDeferred();
  if (errors.length) {
    deferred.reject({ message: errors[0], errors });
  } else {
    deferred.resolve();
  }
  return deferred.promise;
}
